<template>
    <div class="row" style="padding: 8px 0;">
        <el-button @click="scanPay" type="success" size="small" v-hasPerm="['shop:sku:add']">收银</el-button>
        <el-button @click="addDialog" type="primary" size="small" v-hasPerm="['shop:sku:add']">新增商品</el-button>
        <el-button @click="handleImportExcel" type="primary" size="small" v-hasPerm="['shop:sku:add']">导入商品</el-button>
        <el-button @click="handleExport" type="primary" size="small" v-hasPerm="['shop:sku:add']">导出商品</el-button>
        <el-button @click="generateCode" type="primary" size="small" v-hasPerm="['shop:sku:edit']">生成条码</el-button>
        <el-button @click="handlCategory" type="primary" size="small" v-hasPerm="['shop:sku:edit']">商品分类</el-button>
    </div>
    <el-table ref="skuTableRef" :data="skuList" v-loading="loading" row-key="id" stripe max-height="500" show-summary
        :summary-method="getSummaries" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" :selectable="selectable" />
        <el-table-column label="ID" sortable prop="id" align="right" width="70" fixed="left"></el-table-column>
        <el-table-column label="商品名称" prop="name" align="center" width="160" show-overflow-tooltip></el-table-column>
        <el-table-column label="商品简称" prop="shortName" align="center" width="100"></el-table-column>
        <el-table-column label="条码" prop="code" align="center" width="100"></el-table-column>
        <el-table-column label="库存" sortable prop="stock" align="center"></el-table-column>
        <el-table-column label="单位" prop="unit" align="center"></el-table-column>
        <el-table-column label="售价" sortable prop="price" align="center"></el-table-column>
        <el-table-column label="进价" sortable prop="buyPrice" align="center"></el-table-column>
        <el-table-column label="会员价" prop="vipPrice" align="center"></el-table-column>
        <el-table-column label="类型" prop="type" align="center" :filters="categoryFilters"
            :filter-method="filterCategory"></el-table-column>
        <el-table-column label="供货商" prop="supplierId" align="center" :filters="supplierFilters"
            :filter-method="filterSupplier"></el-table-column>
        <el-table-column label="状态" width="80" :filters="[{ text: '在售', value: 1 }, { text: '下架', value: 0 }]"
            :filter-method="filterTag">
            <template #default="scope">
                <el-tag v-if="scope.row.status == 0" type="warning">下架</el-tag>
                <el-tag v-if="scope.row.status == 1" type="success">在售</el-tag>
            </template>
        </el-table-column>

        <el-table-column label="创建时间" prop="createTime" width="150"></el-table-column>
        <el-table-column label="备注" prop="remark" width="100"></el-table-column>

        <el-table-column align="left" label="操作" width="160" fixed="right">
            <template #default="scope">
                <el-button v-hasPerm="['shop:sku:edit']" type="warning" link size="small"
                    @click.stop="editSku(scope.row)">
                    编辑
                </el-button>
                <el-button v-hasPerm="['shop:sku:delete']" type="danger" link size="small"
                    @click.stop="delSku(scope.row.id)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <div class="row">
        <el-pagination layout="sizes, prev, pager, next" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
            :page-size="20" :pager-count="5" :total="totalCount" :current-page="currentPage" @size-change="onSizeChange"
            @current-change="onCurrentChange" />
    </div>

    <sku-import v-model:visible="importDialogVisible" @import-success="handleOpenImportDialogSuccess"></sku-import>
    <sku-info v-model:visible="editDialogVisible" :skuForm="skuForm" :supplierList="supplierList"
        @success="onSuccess"></sku-info>
    <sku-category v-model:visible="categoryDialogVisible" :tree="categoryTree" @controll-success="reloadCategory"
        @choose-success="onCategoryChoose"></sku-category>

    <sku-pay v-model:visible="payDialogVisible" :selectList="selectPaySkuList" @onPayBack="onPayBack"></sku-pay>
</template>

<script setup>
import CategoryApi from '@/api/category';
import SkuApi from '@/api/sku';
import OrderAPI from '@/api/order';

import { ElMessage } from 'element-plus';
import { h } from "vue";
import skuCategory from './components/sku-category.vue';
import skuImport from './components/sku-import.vue';
import skuInfo from './components/sku-info.vue';
import skuPay from './components/sku-pay.vue';

let importDialogVisible = ref(false)
let editDialogVisible = ref(false)
let categoryDialogVisible = ref(false)

let loading = ref(true)

const initData = {
    id: 0,
    name: "",
    shortName: "",
    code: "",
    productNo: "",
    price: 0.00,
    buyPrice: 0.00,
    vipPrice: 0.00,
    type: 0,
    stock: 0,
    unit: "",
    supplierId: "",
    supplierName: "",
    productDate: "", //生产日期
    shelfLife: "", //保质期 天
    status: "1", //1正常, 0下架
}
let skuForm = ref(initData)
let skuList = ref([])

let selectionList = []
let categoryTree = ref([])

function editSku(data) {
    skuForm.value = data
    editDialogVisible.value = true
}

function handleImportExcel() {
    importDialogVisible.value = true
}

function handleOpenImportDialogSuccess() {
    importDialogVisible.value = false
    loadSkuList(currentPage)
}

function handlCategory() {
    categoryDialogVisible.value = true
}

let supplierList = ref([])
let supplierFilters = ref([])
let categoryFilters = ref([])

onMounted(() => {
    loadSkuList(1)
    SkuApi.getSupplierList().then(list => {
        console.log("supplierList:", list)
        supplierFilters.value = list.map(i => {
            return { text: i.name, value: i.id }
        })
        supplierList.value = list
        console.log("supplier:", supplierFilters.value)
    }).catch(e => {
        console.log("supplier-err:", e)
    })
    CategoryApi.listAll().then(list => {
        categoryTree.value = list
        categoryFilters.value = list.map(i => {
            return { text: i.name, value: i.id }
        })
    })
})

let currentPage = 1
let pageSize = ref(20)
let totalPage = ref(1)
let totalCount = ref(0)
function loadSkuList(page) {
    loading.value = true
    SkuApi.list(page, pageSize.value).then(res => {
        skuList.value = res.list
        currentPage = res.currenPage
        totalPage.value = res.totalPage
        totalCount.value = res.totalCount
        loading.value = false
    })
}

function reloadCategory(item) {
    console.log("controll-success", item)
    categoryDialogVisible.value = false
    CategoryApi.listAll().then(list => {
        categoryTree.value = list
    })
}

function onCategoryChoose(category) {
    if (selectionList.length == 0) {
        ElMessage.fail("请至少选择一个商品！");
        return
    }
    categoryDialogVisible.value = false
    let ids = selectionList.map(i => {
        return i.id
    })
    SkuApi.updateSkuCategory(category.id, ids).then(res => {
        loadSkuList(currentPage)
    })
}

function onSizeChange(val) {
    pageSize.value = val
    loadSkuList(1)
}
function onCurrentChange(val) {
    loadSkuList(val)
}
function addDialog() {
    editDialogVisible.value = true
}
function onSuccess() {
    skuForm.value = initData
    editDialogVisible.value = false
}


let skuTableRef = ref()
let selectable = (row) => {
    return true
}
function handleSelectionChange(val) {
    selectionList = val
}

function filterTag(value, row, column) {
    return row.status == value
}

function filterSupplier(value, row, column) {
    return row.supplierId == value
}

function filterCategory(value, row) {
    return row.id == value.type
}

function generateCode() {

}


function handleExport() {
    console.log("eport-data", selectionList)
    if (selectionList.length == 0) {
        ElMessage.warning("请先选择要导出的的商品！")
        return
    }
    loading.value = true
    let ids = selectionList.map(i => i.id)
    SkuApi.export(ids).then((response) => {
        const fileData = response.data;
        const fileName = decodeURI(
            response.headers["content-disposition"].split(";")[1].split("=")[1]
        );
        const fileType =
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

        const blob = new Blob([fileData], { type: fileType });
        const downloadUrl = window.URL.createObjectURL(blob);

        const downloadLink = document.createElement("a");
        downloadLink.href = downloadUrl;
        downloadLink.download = fileName;

        document.body.appendChild(downloadLink);
        downloadLink.click();

        document.body.removeChild(downloadLink);
        window.URL.revokeObjectURL(downloadUrl);

        loading.value = false
    });
}

function getSummaries(params) {
    const { columns, data } = params
    console.log(params)
    let sums = []

    columns.forEach((column, index) => {
        if (index == 0) {
            sums[index] = h('div', { style: {width: "160px"} }, ['合计'])
            return
        }
        if(column.property == "id"){
            sums[index] = data.length
        } else if(column.property == "stock") {
            sums[index] = sum(data, "stock")
        } else if(column.property == "price" || column.property == "buyPrice" || column.property == "vipPrice"){
            const total = sum(data, column.property)
            const avg = total/data.length
            sums[index] = "avg"+avg.toFixed(2)
        } else {
            sums[index] = ""
        }
    })
    return sums
}
function sum(data, column){
    const values = data.map(item => item[column])
    return values.reduce((prev, curr) => {
        let value = Number(curr)
        if (!Number.isNaN(value)) {
            return prev + curr
        } else {
            return prev
        }
    }, 0);
}


let payDialogVisible = ref(false)
let selectPaySkuList = ref([])
function scanPay(){
    if(selectionList.length == 0){
        ElMessage.warning("请选择要支付的商品！")
    } else {
        selectPaySkuList.value = selectionList.filter(i=>i.status!=0).map(item=>{
            return {skuId: item.id, skuName:item.name ,skuCount:1, unitPrice: item.price, salePrice: item.vipPrice}
        })
        console.log("selectPaySkuList", selectPaySkuList.value)
        payDialogVisible.value = true
    }
}


function onPayBack(order){
    loadSkuList(currentPage)  
}
</script>

<style lang="scss" scoped></style>